//
//  HomePageControl.swift
//  banner
//
//  Created by 刘飞 on 2019/6/14.
//  Copyright © 2019 jimubox. All rights reserved.
//

import UIKit

// MARK: - HomePageControl
class Page: UIView {
    let bgLine = UIView()
    let foreLine = UIView()
    var progress: CGFloat = 0.00 {
        didSet {
            foreLine.frame.size.width = progress * bounds.size.width
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
        bgLine.frame = bounds
        foreLine.frame = bounds
        foreLine.frame.size.width = 0
        addSubview(bgLine)
        addSubview(foreLine)
        clipsToBounds = true
        layer.cornerRadius = bounds.size.height / 2.0
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - HomePageControl
class HomePageControl: UIView {
    var numberOfPages: Int = 0 {
        didSet {
            if numberOfPages <= 1 && hidesForSinglePage {
                isHidden = true
                return
            }
            isHidden = false
            reset()
        }
    }
    var currentPage: Int = 0 {
        didSet {
            if numberOfPages <= 1 && hidesForSinglePage {
                return
            }
            if oldValue != currentPage {
                pages[oldValue].progress = 0
            }
            selectedPage = pages[currentPage]
        }
    }
    var hidesForSinglePage: Bool = true
    var pageIndicatorTintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)
    var currentPageIndicatorTintColor = UIColor.white
    var willShowNextPage: (()->())?
    
    var selectedPage: Page?
    private var pages = [Page]()
    
    func updateCurrentPageDisplay() {
        if numberOfPages <= 1 && hidesForSinglePage {
            return
        }
        
        selectedPage?.progress += 0.01
        if (selectedPage?.progress)! >= 1 {
            if let willShowNextPage = willShowNextPage {
                willShowNextPage()
            }
        }
    }
    
    private func reset() {
        for page in pages {
            page.removeFromSuperview()
        }
        pages.removeAll()
        
        let width: CGFloat = 30
        let height: CGFloat = 2
        let y: CGFloat = (bounds.size.height - height) / 2
        let margin: CGFloat = 8
        let leftMargin: CGFloat = (bounds.size.width - width*CGFloat(numberOfPages) - margin*CGFloat(numberOfPages-1)) / 2
        for (index, _) in (0..<numberOfPages).enumerated() {
            let x = leftMargin + (margin + width) * CGFloat(index)
            let page = Page(frame: CGRect(x: x, y: y, width: width, height: height))
            page.bgLine.backgroundColor = pageIndicatorTintColor
            page.foreLine.backgroundColor = currentPageIndicatorTintColor
            addSubview(page)
            pages.append(page)
        }
    }
}
